<?php

namespace Apps\Common\Models;

use Apps\Common\Libs\PicUrl;

/**
 * 用户关注Model
 * @author     chenxiaolin
 * @date        2016年1月19日
 * @version     2.0.0
 * @copyright   Copyright 2016 meelier.com
 */
class UserFollow extends \PhalconPlus\Database\Model
{

    public $id;
    public $user_id;
    public $to_user_id;
    public $type;


    public function getSource()
    {
        return 'user_follow';
    }

    /**
     * Allows to query a set of records that match the specified conditions
     *
     * @param mixed $parameters
     * @return Activity[]
     */
    public static function find($parameters = null)
    {
        return parent::find($parameters);
    }

    /**
     * Allows to query the first record that match the specified conditions
     *
     * @param mixed $parameters
     * @return Activity
     */
    public static function findFirst($parameters = null)
    {
        return parent::findFirst($parameters);
    }

    /**
     * Independent Column Mapping.
     * Keys are the real names in the table and the values their names in the application
     *
     * @return array
     */
    public function columnMap()
    {
        return array(
            'id' => 'id',
            'to_user_id' => 'to_user_id',
            'user_id' => 'user_id',
            'type' => 'type',
        );
    }

    public function defaultColumns()
    {
        return [
        ];
    }

    /**
     * 关注用户
     * @param int $user_id 关注用户id
     * @param int $to_user_id 被关注用户id
     * @param int $type 类型 【1=》普通用户，2=》专家】
     * @return bool
     */
    public function follow($user_id, $to_user_id, $type = 1)
    {
        $type = $type == 2 ? 2 : 1;
        return $this->save([
            'user_id' => $user_id,
            'to_user_id' => $to_user_id,
            'type' => $type
        ]);
    }

    /**
     * 取消关注用户
     * @param $user_id
     * @param $to_user_id
     * @param int $type
     * @return bool
     */
    public function unFollow($user_id, $to_user_id, $type = 1)
    {
        if ($model = self::findFirst("user_id = {$user_id} and to_user_id = {$to_user_id} and type = {$type}")) {
            return $model->delete();
        }
        return false;
    }

    /**
     * 是否关注过
     * @param $user_id
     * @param $to_user_id
     * @param int $type 【1=》普通用户，2=》专家】
     * @return int
     */
    public function is_follow($user_id, $to_user_id, $type = 1)
    {
        return self::count(['conditions' => "user_id = {$user_id} and to_user_id = {$to_user_id} and type = {$type}"]);
    }

    /**
     * 获取用户的关注数
     * @param $user_id
     * @param int $type
     * @return mixed
     */
    public function getFollowCount($user_id, $type = 1)
    {
        return self::count("user_id = {$user_id} and type = {$type}");
    }

    /**
     * 获取用户的被关注数
     * @param int $user_id 用户id
     * @param int $type 类型 【1=》普通用户，2=》专家】
     * @return mixed
     */
    public function getToFollowCount($user_id, $type = 1)
    {
        return self::count("to_user_id = {$user_id} and type = {$type}");
    }

    /**
     * 用户的关注列表（普通用户）
     * @param int $user_id 用户id
     * @param int $offset 分页偏移量
     * @param int $limit 页大小
     * @return array
     */
    public function getFollowList($user_id, $offset = 0, $limit = 10)
    {
        $list = self::query()->columns([
            'u.user_id',
            'u.user_gender',
            'u.user_cover',
            'u.user_nickname'
        ])->leftJoin('\Apps\Common\Models\UserBase', 'u.user_id = \Apps\Common\Models\UserFollow.to_user_id', 'u')->where("\\Apps\\Common\\Models\\UserFollow.user_id = {$user_id} and type = 1")->limit($limit, $offset)->execute()->toArray();

        foreach ($list as $k => $val) {
            if (!preg_match('/^http/', $val['user_cover'])) {
                $list[$k]['user_cover'] = PicUrl::ActivityCover($val['user_cover'], $this->getDi());
            }
            $list[$k]['follow_count'] = $this->getFollowCount($val['user_id'], 1);
            $list[$k]['fans_count'] = $this->getToFollowCount($val['user_id'], 1);
        }

        return $list;
    }

    /**
     * 用户的关注列表（关注的专家）
     * @param int $user_id 用户id
     * @param int $offset 偏移量
     * @param int $limit 页大小
     * @return mixed
     */
    public function getFollowExpertList($user_id, $offset = 0, $limit = 10)
    {
        $list = self::query()->columns([
            'u.user_id',
            'u.user_gender',
            'u.user_cover',
            'u.user_nickname',
            'a.attr_value_json'
        ])->leftJoin('\Apps\Common\Models\UserBase', 'u.user_id = \Apps\Common\Models\UserFollow.to_user_id', 'u')->leftJoin('\Apps\Common\Models\UserAttribute', 'a.user_id = \Apps\Common\Models\UserFollow.to_user_id and a.attr_type = 103 and a.attr_state = 1', 'a')->where("\\Apps\\Common\\Models\\UserFollow.user_id = {$user_id} and type = 2")->limit($limit, $offset)->execute()->toArray();
        // 上面这里的关联查询，如果对应的专家扩展模型没有有效的数据，则这条数据就不会出现

        foreach ($list as $k => $val) {
            if (!preg_match('/^http/', $val['user_cover'])) {
                $list[$k]['user_cover'] = PicUrl::ActivityCover($val['user_cover'], $this->getDi());
            }
            $list[$k]['expert_follow_count'] = $this->getToFollowCount($val['user_id'], 2);

            // 组合专家的扩展信息
            $info = json_decode($val['attr_value_json']);
            $list[$k]['experience'] = $info->experience ?: ''; // 从业经验
            $list[$k]['experttitle'] = $info->experttitle ?: ''; // 擅长领域
            $list[$k]['field'] = $info->field ?: []; // 专家头衔(array)

            unset($list[$k]['attr_value_json']);
        }

        return $list;
    }

}
